package com.ruyuan.rapid.core;

import com.ruyuan.rapid.common.constants.RapidBufferHelper;
import com.ruyuan.rapid.core.netty.NettyHttpClient;
import com.ruyuan.rapid.core.netty.NettyHttpServer;
import com.ruyuan.rapid.core.netty.processor.NettyBatchEventProcessor;
import com.ruyuan.rapid.core.netty.processor.NettyCoreProcessor;
import com.ruyuan.rapid.core.netty.processor.NettyMpmcProcessor;
import com.ruyuan.rapid.core.netty.processor.NettyProcessor;
import lombok.extern.slf4j.Slf4j;

/**
 * 生命周期的容器组件
 * @author mac
 */
@Slf4j
public class RapidContainer implements LifeCycle {

    /**
     * 核心配置类
     */
    private final RapidConfig rapidConfig;
    /**
     * 接收http请求的server
     */
    private NettyHttpServer nettyHttpServer;
    /**
     * 转发的httpclient
     */
    private NettyHttpClient nettyHttpClient;
    /**
     * 核心处理器
     */
    private NettyProcessor nettyProcessor;

    public RapidContainer(RapidConfig rapidConfig) {
        this.rapidConfig = rapidConfig;
        init();
    }

    /**
     * 生命周期组件的初始化
     */
    @Override
    public void init() {
        // 1. 构建核心处理器
        NettyCoreProcessor nettyCoreProcessor = new NettyCoreProcessor();
        // 2. 是否开启缓冲
        String bufferType = rapidConfig.getBufferType();
        if (RapidBufferHelper.isFlusher(bufferType)) {
            nettyProcessor = new NettyBatchEventProcessor(rapidConfig, nettyCoreProcessor);
        } else if (RapidBufferHelper.isMpmc(bufferType)) {
            nettyProcessor = new NettyMpmcProcessor(rapidConfig, nettyCoreProcessor, true);
        } else {
            this.nettyProcessor = nettyCoreProcessor;
        }

        // 创建HttpServer
        this.nettyHttpServer = new NettyHttpServer(rapidConfig, nettyProcessor);
        // 创建HttpClient
        nettyHttpClient = new NettyHttpClient(rapidConfig, nettyHttpServer.getEventLoopGroupWork());
    }

    /**
     * 生命周期组件的启动方法
     */
    @Override
    public void start() {
        nettyProcessor.start();
        nettyHttpServer.start();
        nettyHttpClient.start();
        log.info("RapidContainer started !");
    }

    /**
     * 关闭方法
     */
    @Override
    public void shutdown() {
        nettyProcessor.shutdown();
        nettyHttpServer.shutdown();
        log.info("RapidContainer shutdown !");
    }
}
